package com.zjhcsoft.auth.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zjhcsoft.auth.common.vo.Result;
import com.zjhcsoft.auth.entity.AppResource;
import com.zjhcsoft.auth.entity.Channel;
import com.zjhcsoft.auth.entity.Corporation;
import com.zjhcsoft.auth.service.AppResourceService;
import com.zjhcsoft.auth.service.ChannelService;
import com.zjhcsoft.auth.service.CorporationService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 渠道表 前端控制器
 * </p>
 *
 * @author wzya
 * @since 2021-03-29
 */
@Controller
@RequestMapping("/channel")
public class ChannelController {

    @Autowired
    ChannelService channelService;
    @Autowired
    CorporationService corporationService;
    @Autowired
    AppResourceService appService;

    @PostMapping("/add")
    @ResponseBody
    @ApiOperation(value="渠道新增")
    public Result add(Channel channel){

        List<Corporation> corporations = corporationService.query().list();
        if(null!=corporations && corporations.size()>0){
            channelService.save(channel);
            List<AppResource> apps = corporations.stream().map(corporation -> new AppResource(){
                {
                    setCorporationId(corporation.getId());
                    setChannelId(channel.getId());
                    setDefaultCredentialType(channel.getDefaultCredentialType());
                    setAppCode(channel.getChannelName()+"_"+corporation.getCorporationName());
                }
            }).collect(Collectors.toList());
            appService.saveBatch(apps);
        }else {
            channelService.save(channel);
        }
        return Result.ok();
    }

    @PostMapping("/query")
    @ResponseBody
    @ApiOperation(value="渠道查询")
    public Result query(){
        return Result.ok(channelService.query().list());
    }


    @PostMapping("/del")
    @ResponseBody
    @ApiOperation(value="渠道删除")
    public Result del(String channelCode){

        //TODO..用户绑定校验
        UpdateWrapper<Channel> wrapper = new UpdateWrapper<>();
        wrapper.lambda().eq(Channel::getChannelCode,channelCode);
        return Result.ok(channelService.remove(wrapper));
    }



}

